from django.shortcuts import render
from django.views import View
from django import http
import logging, json, re
from django.contrib.auth import login, authenticate, logout
from django_redis import get_redis_connection
from celery_tasks.email.tasks import send_email_verify_url

from apps.users.models import User
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from apps.users.utils import generate_email_verify_url, check_email_verify_url
# Create your views here.
# 日志输出器
logger = logging.getLogger('django')


class EmailActiveView(View):
    """验证激活邮箱
    PUT /emails/verification/
    """

    def put(self, request):
        """实现验证激活邮箱的逻辑"""
        # 接收参数
        token = request.GET.get('token')

        # 校验参数
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少token'})

        # 实现核心逻辑
        # 通过token提取要验证邮箱的用户
        user = check_email_verify_url(token=token)

        # 将要验证邮箱的用户的email_active字段设置True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱验证失败'})

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '邮箱验证成功'})


class EmailView(LoginRequiredJSONMixin, View):
    """添加邮箱
    PUT /emails/
    """
    def put(self, request):
        """实现添加邮箱的逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 校验邮箱格式
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '参数email格式错误'})

        # 实现核心逻辑：添加邮箱就是将用户填写的邮箱地址保存到当前登录用户的email字段即可
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '添加邮箱失败'})

        # 发送邮箱的验证激活邮件：耗时操作，不能让他阻塞主逻辑，需要从主逻辑中解耦出来，celery
        # verify_url = '测试的激活链接'
        verify_url = generate_email_verify_url(user=request.user)
        send_email_verify_url.delay(email, verify_url)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK'})


class UserInfoView(LoginRequiredJSONMixin, View):
    """用户中心
    GET /info/
    """
    def get(self, request):
        """实现用户中心数据展示
        由于我们在该接口中，判断了用户是否时登录用户
        所以能进入到该接口的，一定是登录用户发送的
        所以request.user里面获取的用户信息一定是当前登录的用户信息
        """
        data_dict = {
            'code': 0,
            'errmsg': 'OK',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
            }
        }
        return http.JsonResponse(data_dict)


# class UserInfoView(View):
#     """用户中心
#     GET /info/
#     """
#     def get(self, request):
#         """实现用户中心数据展示"""
#         # 使用authenticated判断是否登录
#         if not request.user.is_authenticated:
#             # False 未登录
#             return http.JsonResponse({'code': 400, 'errmsg': ''})
#         # True 登录
#         data_dict = {
#             'code': 0,
#             'errmsg': 'OK',
#             'info_data': {
#                 'username': '',
#                 'mobile': '',
#                 'email': '',
#                 'email_active': ''
#             }
#         }
#         return http.JsonResponse(data_dict)


class LogoutView(View):
    """退出登录
    DELETE /logout/
    """

    def delete(self, request):
        """实现退出登录的逻辑
        退出登录的逻辑正好跟登录相反
        退出清理登录状态
        退出登录需要清理用户名cookie
        """
        # 清理登录状态
        logout(request)
        # 清理用户名cookie
        response = http.JsonResponse({'code': '0', 'errmsg': '退出登录成功'})
        response.delete_cookie('username')

        return response


class LoginView(View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        account = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 校验
        if not all([account, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '参数password格式错误'})

        # 实现多账号登录
        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 认证登录用户
        user = authenticate(request=request, username=account, password=password)

        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})

        login(request, user)

        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        # 在登录成功后，将用户名写入到cookie，将来会在页面右上角展示
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

        # 响应结果
        return response


class RegisterView(View):
    """用户注册

    """

    def post(self, request):
        """实现注册逻辑"""
        # 接收参数:请求体中的JSON数据
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)
        # json_dict = json.loads(request.body.decode())

        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        # 提取短信验证码
        sms_code_clinet = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        # 校验参数
        # 判断是否缺少必传参数
        if not all([username, password, password2, mobile, sms_code_clinet, allow]):
            return http.JsonResponse({'code': '400', 'errmsg': '缺少必传的参数'})

        # 判断用户名是否满足项目格式要求
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': '400', 'errmsg': '参数username有误'})

        # 判断password
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': '400', 'errmsg': '参数password有误'})

        # 判断password2 和 password
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对'})

        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        # 判断短信验证码是否正确
        # 提取服务端存储的短信验证码
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        if sms_code_clinet != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        # 7.allow检验
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误'})

        # 实现核心逻辑:保存注册数据到用户数据表
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败'})

        # 实现状态保持
        login(request, user)

        # 在注册成功后，将用户名写入到cookie，将来会在页面右上角展示
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

        # 响应结果
        return response


class UsernameCountView(View):
    """判断用户名是否重复注册
    GET http://www.meiduo.site:8000/usernames/itcast/count/
    """

    def get(self, request, username):
        """查询用户名对应的记录个数"""
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': '400', 'errmsg': '数据错误'})

        return http.JsonResponse({'code': '0', 'errmsg': 'OK', 'count': count})


class MobileCountView(View):

    def get(self, request, mobile):
        """判断手机号是否重复注册"""
        # 1.查询mobile在mysql中的个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '查询数据库出错'})

        # 2.返回结果(json)
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})
